# -*- coding: utf-8 -*-
import requests
import sys
import json

baseurl = sys.argv[1]
idata_configure_file = sys.argv[2]
username = "admin"
passwd = "123456"

headers = {
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'
}


def add_IData_Job(configure_file, jobGroup="1"):
    iData_config = json.load(open(configure_file))
    s = login(username, passwd)
    for job in iData_config:
        job_param = iData_config.get(job)
        job_param.update({"jobGroup": jobGroup})
        s.post(baseurl + "/jobinfo/add", data=job_param, headers=headers)
        print "Add Job {0} to jobGroup {1}".format(job, jobGroup)


def login(username="admin", password="123456"):
    login_param = {"userName": username, "password": password}
    session = requests.Session()
    response = session.post(baseurl + "/login", data=login_param, headers=headers)
    if json.loads(response.content).get("code") == 200:
        print "Login XXL-JOB OK"
        return session
    else:
        print "Login XXL-JOB Fail"
        exit(-1)


if __name__ == "__main__":
    add_IData_Job(idata_configure_file)
